package com.book.servlet.action;

import com.book.entity.Book;
import com.book.entity.User;
import com.book.service.BookService;
import com.book.service.impl.BookServiceImpl;
import com.book.utils.ThymeleafUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.context.Context;

import java.io.IOException;

@WebServlet("/add-book")
public class AddBookServlet extends HttpServlet {
    BookService bookService;

    @Override
    public void init() throws ServletException {
        bookService = new BookServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        User user = (User) req.getSession().getAttribute("user");
        if (req.getSession().getAttribute("exist") != null) {
            context.setVariable("exist",1);
            req.getSession().removeAttribute("exist");
        }
        if (req.getSession().getAttribute("warning") != null){
            context.setVariable("warning",1);
            req.getSession().removeAttribute("warning");
        }
        context.setVariable("nickName",user.getNickname());
        ThymeleafUtil.process("add_book.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if(!req.getParameter("bookId").isEmpty() & !req.getParameter("bookName").isEmpty() & !req.getParameter("bookNumber").isEmpty()){
            String bookId = req.getParameter("bookId");
            String bookName = req.getParameter("bookName");
            String bookNumber = req.getParameter("bookNumber");
            if (bookService.selectBookById(Integer.valueOf(bookId)) != null) {
                req.getSession().setAttribute("exist", 1);
                resp.sendRedirect("add-book");
                return;
            }
            bookService.insertBook(new Book(Integer.valueOf(bookId), bookName, Integer.valueOf(bookNumber)));
            resp.sendRedirect("books");
        }else {
            req.getSession().setAttribute("warning", 1);
            resp.sendRedirect("add-book");
        }
    }
}
